<template>
  <div class="app-container">
    <el-card>
    <el-form :model="teacherForm" :rules="rules" ref="teacherForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="teacherForm.name"></el-input>
      </el-form-item>
      <el-form-item label="讲师级别" prop="level" required>
        <el-select v-model="teacherForm.level" placeholder="请选择活动区域">
          <el-option label="请选择" :value="0"></el-option>
          <el-option label="高级讲师" :value="1"></el-option>
          <el-option label="首席讲师" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="加入时间" required>
        <el-col :span="11">
          <el-form-item prop="joinDate">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="teacherForm.joinDate"
              style="width: 100%;"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="说明" prop="career">
        <el-input  type="textarea" v-model="teacherForm.career"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="intro">
        <el-input type="textarea" v-model="teacherForm.intro"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:8002/api/oss/upload-image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error = "imageUploadError"
        >
          <img v-if="teacherForm.avatar" :src="teacherForm.avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('teacherForm')">{{(teacherForm.id != null)?'更新教师':'增加教师'}}</el-button>
        <el-button @click="resetForm('teacherForm')">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
  </div>
</template>

<script>

  import * as TeacherApi from "../../api/teacher"

  import {objExcludeNullToMap} from "../../utils"

  export default {
    name: 'teacherManager',
    data() {


      let validateLevel = (rule, value, callback) => {
        if (value == undefined || value == null || value == 0) {

          callback(new Error('请选择教师等级'));
        } else {

          callback();
        }
      };


      return {

        teacherForm: {
          id: null,
          name: '',
          level: 0,
          joinDate: '',
          career: '',
          intro: '',
          avatar: '',
          sort: 0
        },
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          level: [
            { validator: validateLevel, trigger: 'blur' }
          ],
          joinDate: [
            {required: true, message: '请选择日期', trigger: 'change' }
          ]
        },
        loading: null
      };
    },
    created: function(){

      this.teacherForm.id = this.$route.params.id
      this.loadTeacher();
    },
    methods: {
      submitForm(formName) {


        this.$refs[formName].validate((valid) => {
          if (valid) {

            let condition = objExcludeNullToMap(this.teacherForm);

            if (this.teacherForm.id == null){

              // 插入
              this.addTeacher(condition);

            }else {

              //更新
              this.updateTeacher(condition);
            }

          } else {


            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      handleAvatarSuccess(response, file, fileList){

        if (this.loading != null){

          this.loading.close();
          this.loading = null;
        }


        if (response.code != 0){

          this.$message.error("图片上传失败");
        }

        this.teacherForm.avatar = response.data.imageUrl;

      },
      beforeAvatarUpload(){

        this.loading = this.$loading({
          lock: true,
          text: '上传图片中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      },
      imageUploadError(){

        if (this.loading != null){

          this.loading.close();
          this.loading = null;
        }

        this.$message.error("图片上传失败");
      },
      async loadTeacher(){

        if (this.teacherForm.id == undefined || this.teacherForm.id == null || this.teacherForm.id == ''){

          return;
        }

        this.teacherForm = await TeacherApi.findTeacherById(this.teacherForm.id);

      },

      async addTeacher(data){

         await TeacherApi.insertTeacher(data);

          this.$router.push("/teacher/list")

      },

      async updateTeacher(data){

        await TeacherApi.updateTeacher(data);

        this.$router.push("/teacher/list")

      }
    }
  }
</script>

<style scoped>

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
